﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using S7.Net;
using System.Configuration;
using KD.Sms.Card;
using System.Runtime.Remoting.Messaging;

namespace KD.Sms.Monitor
{
    public partial class frmPail : Form
    {
        bool _bIsBusy = false;
        bool _bWeightTare = false;
        bool _bWeightGross = false;
        bool _bSendStartCmd = false;
        bool _bSend开始放样 = false;
        bool _bNeedSend开始放样 = false;
        bool _b读写卡Complete = false;
        bool _b读写卡Success = false;
        bool _b读写卡Started = false;
        bool _b读写卡Need = false;
        bool _bSavePaiEnd = false;
        bool _bOpenPailErrorReSetCommand = false;

        string _strPLY650Ip, _strStm32ip, _strPLY650Com;
        int _strPLY650Port, _strStm32Port;
        double _dWeightRevise = 0;

        private Hashtable _hasPails = new Hashtable();
        private Hashtable _hasPailsState = new Hashtable();
        private DataTable _tabSource = new DataTable();
        private DataRow[] _drSelect;
        private decimal E_WeightNow = 0;
        Card.Stm32Main E_Rfid = null;
        Entity.SamplingInfoForPailSave _modelSave;
        object _objLock启动读卡 = new object();
        object _objLock开始放样 = new object();
        object _objLock开盖异常 = new object();
        /// <summary>
        /// 采样样品皮重
        /// </summary>
        public static decimal E_SampleWeightTare { set; get; }
        /// <summary>
        /// 毛重
        /// </summary>
        public static decimal E_SampleWeightGross { set; get; }
        /// <summary>
        /// 样品重量
        /// </summary>
        public static decimal E_SampleWeightNet { set; get; }

        public frmPail()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmPail_Load(object sender, EventArgs e)
        {
            _bWeightTare = false;
            _bWeightGross = false;
            labCurrentCar.Text = string.Empty;
            labCurrentPail.Text = string.Empty;
            labLdWeight.Text = "######";
            _hasPails.Add(1, pail1);
            _hasPails.Add(2, pail2);
            _hasPails.Add(3, pail3);
            _hasPails.Add(4, pail4);
            _hasPails.Add(5, pail5);
            _hasPails.Add(6, pail6);

            UI.KdPail Pail;
            for (int i = 1; i <= 6; i++)
            {
                Pail = (UI.KdPail)_hasPails[i];
                Pail.C_PailName = i.ToString();
                Pail.C_PointCount = string.Empty;
                Pail.C_SampleCode = string.Empty;
                Pail.C_Weight = string.Empty;
                //装载
                _hasPailsState.Add(i, 1);
            }

            Task.Fzj.Instance.PlcDataReadOut += OnPlcDataReadOut;
            ActionCenter.Action.Instance.RefreshSamplingPail += OnRefreshSamplingPail;
            ActionCenter.Action.Instance.WeightSampleTare += OnWeightSampleTare;
            ActionCenter.Action.Instance.WeightSampleGross += OnWeightSampleGross;
            ActionCenter.Action.Instance.SamplingAndMakingEnd += OnSamplingAndMakingEnd;
            ActionCenter.Action.Instance.LayingOffComplete += OnLayingOffComplete;
            DoQueryPailsStatus();

            _strPLY650Ip = System.Configuration.ConfigurationManager.AppSettings["PLY650IP"].ToString();
            _strPLY650Com = System.Configuration.ConfigurationManager.AppSettings["PLY650Com"].ToString();
            _strPLY650Port = int.Parse(System.Configuration.ConfigurationManager.AppSettings["PLY650Port"].ToString());
            _strStm32ip = System.Configuration.ConfigurationManager.AppSettings["Stm32IP"].ToString();
            _strStm32Port = int.Parse(System.Configuration.ConfigurationManager.AppSettings["Stm32Port"].ToString());
            _dWeightRevise = double.Parse(System.Configuration.ConfigurationManager.AppSettings["WeightRevise"].ToString());
            //初始化样桶读卡对象
            E_Rfid = new Card.Stm32Main();
            ActionCenter.Action.Instance.ReadCardStm32 += OnReadCardStm32;

            DataTable _tabConfig = DAL.SqlLite.Main.Instance.DoQueryWaringParmsForSampleWeight();
            if (_tabConfig != null && _tabConfig.Rows.Count == 1)
            {
                CacheSystemControl.E_SampleWeightMinValue = Convert.ToDecimal(_tabConfig.Rows[0]["MinWeight"].ToString());
                CacheSystemControl.E_SampleWeightMaxValue = Convert.ToDecimal(_tabConfig.Rows[0]["MaxWeight"].ToString());
                CacheSystemControl.E_MemoryReductionc = _tabConfig.Rows[0]["MemoryReductionc"] != DBNull.Value && (_tabConfig.Rows[0]["MemoryReductionc"].ToString() == "1" || _tabConfig.Rows[0]["MemoryReductionc"].ToString() == "是");
                CacheSystemControl.E_ReductioncDefaultSet = Convert.ToInt32(_tabConfig.Rows[0]["DefaultReductionc"].ToString());
            }
            else
            {
                CacheSystemControl.E_SampleWeightMinValue = Convert.ToDecimal("0.50");
                CacheSystemControl.E_SampleWeightMaxValue = Convert.ToDecimal("4.55");
                CacheSystemControl.E_MemoryReductionc = false;
                CacheSystemControl.E_ReductioncDefaultSet = 50;
            }
        }

        /// <summary>
        /// 刷新界面样桶数据
        /// </summary>
        /// <param name="send"></param>
        /// <param name="e"></param>
        private void OnRefreshSamplingPail(object send, ActionCenter.CommonEventArgs e)
        {
            DoQueryPailsStatus();
        }

        /// <summary>
        /// 样品皮重称重
        /// </summary>
        /// <param name="send"></param>
        /// <param name="e"></param>
        private void OnWeightSampleTare(object send, ActionCenter.CommonEventArgs e)
        {
            _bWeightGross = false;
            _bSendStartCmd = false;
            if (!_bWeightTare)
            {
                E_SampleWeightTare = E_WeightNow;
                FormHelper.ApplicationShow(UI.MsgType.Error, string.Format("采样结束回卸料点，记录皮重:{0}kg", E_SampleWeightTare));
            }
        }

        /// <summary>
        /// 修改样品重量记录
        /// </summary>
        /// <param name="send"></param>
        /// <param name="e"></param>
        private void OnWeightSampleGross(object send, ActionCenter.CommonEventArgs e)
        {
            _bWeightTare = false;
            _bSendStartCmd = false;
            if (!_bWeightGross)
            {
                E_SampleWeightGross = E_WeightNow;
                E_SampleWeightNet = E_SampleWeightGross - E_SampleWeightTare;
                FormHelper.ApplicationShow(UI.MsgType.Error, string.Format("采样完成，记录毛重:{0}kg 皮重:{1}kg 净重:{2}kg", E_SampleWeightGross, E_SampleWeightTare, E_SampleWeightNet));
                if (DAL.SqlLite.Main.Instance.DoUpdateSamplingEndPailWeight(E_SampleWeightNet + Convert.ToDecimal("0.06"), CacheSamplingPacking.E_PackingSaveValueGet.E_SamplingIdIfLocal))
                    FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("{0}样品重量记录成功", CacheSamplingPacking.E_PackingSaveValueGet.E_SamplingCarNum));
                else
                    FormHelper.ApplicationShow(UI.MsgType.Error, string.Format("{0}样品重量记录失败", CacheSamplingPacking.E_PackingSaveValueGet.E_SamplingCarNum));
            }
        }

        /// <summary>
        /// 采样后制样完成
        /// </summary>
        /// <param name="send"></param>
        /// <param name="e"></param>
        private void OnSamplingAndMakingEnd(object send, ActionCenter.CommonEventArgs e)
        {
            if (!_bSendStartCmd)
            {
                _bSavePaiEnd = false;
                _modelSave = CacheSamplingPacking.E_PackingSaveValueGet;
                UI.FormHelper.SetControlText(labCurrentCar, _modelSave.E_SamplingCarNum);
                UI.FormHelper.SetControlText(labCurrentPail, _modelSave.E_SamplingPail.ToString() + "#桶");
                _bSendStartCmd = DoSendCommand();
            }
        }

        /// <summary>
        /// 强制放样完成
        /// </summary>
        /// <param name="send"></param>
        /// <param name="e"></param>
        private void OnLayingOffComplete(object send, ActionCenter.CommonEventArgs e)
        {
            FormHelper.ApplicationShow(UI.MsgType.Error, "收到强制放样完成信号!");
            LayingOffComplete();
        }
        /// <summary>
        /// 发送转桶指令
        /// </summary>
        /// <returns></returns>
        private bool DoSendCommand()
        {
            bool _bResult = false;
            if (_modelSave.E_SamplingPail <= 0)
            {
                FormHelper.ApplicationShow(UI.MsgType.Error, "封装机当前当前桶号参数输入不正确!");
                return false;
            }
            //写入桶号
            if (Task.Fzj.Instance.DoWrite(60, (short)_modelSave.E_SamplingPail))
            {
                FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("往封装机写入采样桶号{0}成功!", _modelSave.E_SamplingPail));
                //开始转桶
                if (Task.Fzj.Instance.DoWrite(52, (short)300))
                {
                    FormHelper.ApplicationShow(UI.MsgType.Information, "往封装机写入开始转桶指令成功!");
                    _bResult = true;
                }
                else
                    FormHelper.ApplicationShow(UI.MsgType.Error, "往封装机写入开始转桶指令失败!详见日志!");
            }
            else
                FormHelper.ApplicationShow(UI.MsgType.Error, "往封装机写入采样桶号失败!详见日志!");
            return _bResult;
        }

        /// <summary>
        /// 查询所有样桶
        /// </summary>
        private void DoQueryPailsStatus()
        {
            _tabSource = DAL.SqlLite.Main.Instance.DoQueryPailForMonitor();
            UI.KdPail Pail;
            for (int i = 1; i <= 6; i++)
            {
                Pail = (UI.KdPail)_hasPails[i];
                if (Pail != null)
                {
                    Pail.C_HavePail = _hasPailsState[i].ToString() == "1";
                    _drSelect = _tabSource.Select(string.Format(" PailId = {0}", i));
                    if (_drSelect != null && _drSelect.Length == 1)
                    {
                        Pail.C_Weight = _drSelect[0]["Weight"].ToString();
                        Pail.C_PointCount = _drSelect[0]["CurrentValue"].ToString();
                        Pail.C_SampleCode = _drSelect[0]["Codes"].ToString();
                    }
                    else
                    {
                        Pail.C_Weight = string.Empty;
                        Pail.C_PointCount = string.Empty;
                        Pail.C_SampleCode = string.Empty;
                    }
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="send"></param>
        /// <param name="e"></param>
        int _iWeight = 0;
        private void OnPlcDataReadOut(object send, Task.ActiveReadEventArgs e)
        {
            if (_bIsBusy)
                return;
            try
            {
                _bIsBusy = true;
                short[] _arrReads = (short[])e.E_ReadValue;
                int[] _aryBits76 = DataConvert.Ushort2Binary((int)(_arrReads[76 / 2]));
                int[] _aryBits54 = DataConvert.Ushort2Binary((int)(_arrReads[54 / 2]));

                int _aryBits56 = (int)(_arrReads[56 / 2]);
                _hasPailsState[1] = _aryBits76[1];
                _hasPailsState[2] = _aryBits76[2];
                _hasPailsState[3] = _aryBits76[3];
                _hasPailsState[4] = _aryBits76[4];
                _hasPailsState[5] = _aryBits76[5];
                _hasPailsState[6] = _aryBits76[6];
                /*
                * 解析仪表重量
                */
                _iWeight = (int)(_arrReads[0 / 2].ConvertToUshort());
                if (_iWeight > 32767)
                    _iWeight = _iWeight - 65536;
                E_WeightNow = Convert.ToDecimal(_iWeight * 1.0 / 100);
                CacheMemoryCenter.E_SampleWeight = Convert.ToDecimal(_iWeight * 1.0 / 100 * 1000);
                UI.FormHelper.SetControlText(labLdWeight, E_WeightNow.ToString() + "kg");
                //解析一些状态
                CacheMemoryCenter.E_PackingMachineState.准备好 = _aryBits54[0] == 1;
                CacheMemoryCenter.E_PackingMachineState.复位运行 = _aryBits54[1] == 1;
                CacheMemoryCenter.E_PackingMachineState.放样运行 = _aryBits54[2] == 1;
                CacheMemoryCenter.E_PackingMachineState.放样结束 = _aryBits54[3] == 1;
                CacheMemoryCenter.E_PackingMachineState.所有样桶满 = _aryBits54[6] == 1;
                CacheMemoryCenter.E_PackingMachineState.皮带联锁 = _aryBits54[7] == 1;
                CacheMemoryCenter.E_PackingMachineState.缩分完成 = _aryBits54[8] == 1;
                CacheMemoryCenter.E_PackingMachineState.开盖异常 = _aryBits54[9] == 1;
                CacheMemoryCenter.E_PackingMachineState.总故障位 = _aryBits54[10] == 1;
                CacheMemoryCenter.E_PackingMachineState.称重触发 = _aryBits54[11] == 1;
                CacheMemoryCenter.E_PackingMachineState.写卡触发 = _aryBits54[12] == 1;
                CacheMemoryCenter.E_PackingMachineState.设备原位 = _aryBits54[13] == 1;
                CacheMemoryCenter.E_PackingMachineState.自动模式 = _aryBits54[14] == 1;
                CacheMemoryCenter.E_PackingMachineState.手动模式 = _aryBits54[15] == 1;
                CacheMemoryCenter.E_PackingMachineState.自动准备好 = CacheMemoryCenter.E_PackingMachineState.准备好 && CacheMemoryCenter.E_PackingMachineState.自动模式;

                //解析仪表重量
                var weight = string.Empty;
                //UI.FormHelper.SetControlText(labLdWeight, string.IsNullOrEmpty(weight) ? "0.00" : weight);
                //解析当前流程
                if (_aryBits56 == 0)
                    UI.FormHelper.SetControlText(labFlowInfo, "自动流程未启动等待运行");
                else if (_aryBits56 == 1)
                    UI.FormHelper.SetControlText(labFlowInfo, "样桶校桶开始");
                else if (_aryBits56 == 2)
                    UI.FormHelper.SetControlText(labFlowInfo, "样桶校桶运行");
                else if (_aryBits56 == 3)
                    UI.FormHelper.SetControlText(labFlowInfo, "样桶定位开始");
                else if (_aryBits56 == 4)
                    UI.FormHelper.SetControlText(labFlowInfo, "样桶定位运行");
                //else if (_aryBits56 == 5)
                //    UI.FormHelper.SetControlText(labMainInfo, "样桶自动开锁");
                //else if (_aryBits56 == 6)
                //    UI.FormHelper.SetControlText(labMainInfo, "样桶开锁运行");
                else if (_aryBits56 == 7)
                    UI.FormHelper.SetControlText(labFlowInfo, "开关盖机构下降");
                else if (_aryBits56 == 8)
                    UI.FormHelper.SetControlText(labFlowInfo, "开关盖机构下降运行");
                else if (_aryBits56 == 9)
                    UI.FormHelper.SetControlText(labFlowInfo, "开关盖机构开盖");
                else if (_aryBits56 == 10)
                    UI.FormHelper.SetControlText(labFlowInfo, "开关盖机构开盖运行");
                else if (_aryBits56 == 11)
                    UI.FormHelper.SetControlText(labFlowInfo, "开盖到位判断");
                else if (_aryBits56 == 12)
                    UI.FormHelper.SetControlText(labFlowInfo, "料斗去放样位");
                else if (_aryBits56 == 13)
                    UI.FormHelper.SetControlText(labFlowInfo, "料斗去放样位运行");
                else if (_aryBits56 == 14)
                    UI.FormHelper.SetControlText(labFlowInfo, "料斗回安全位");
                else if (_aryBits56 == 15)
                    UI.FormHelper.SetControlText(labFlowInfo, "料斗回安全位运行");
                else if (_aryBits56 == 16)
                    UI.FormHelper.SetControlText(labFlowInfo, "开关盖机构关盖");
                else if (_aryBits56 == 17)
                    UI.FormHelper.SetControlText(labFlowInfo, "开关盖机构关盖运行");
                else if (_aryBits56 == 18)
                    UI.FormHelper.SetControlText(labFlowInfo, "开关盖机构上升");
                else if (_aryBits56 == 19)
                    UI.FormHelper.SetControlText(labFlowInfo, "开关盖机构上升运行");


                SetUI_OpenClose();

                /*
                * 写卡触发,上位机自己玩
                * 没有写卡触发信号就根据动作流程判断
                */
                if (CacheMemoryCenter.E_PackingMachineState.写卡触发)
                {
                    lock (_objLock启动读卡)
                    {
                        if (!_b读写卡Started)
                        {
                            _bSend开始放样 = false;
                            _bNeedSend开始放样 = false;
                            _b读写卡Need = true;
                            _b读写卡Started = true;
                            _b读写卡Complete = false;
                            _b读写卡Success = false;
                            FormHelper.ApplicationShow(UI.MsgType.Information, "收到写卡触发信号!启动样桶读卡");
                            E_Rfid.DoRead(_strStm32ip, _strStm32Port, false);
                        }
                    }
                }
                //else
                //{
                //    /*
                //    * 补丁，放样过程中亦启动读卡
                //    */
                //    if (_aryBits56 >= 8 && _aryBits56 <= 16)
                //    {
                //        if (!_b读写卡Started)
                //        {
                //            if (!_b读写卡StarteReplenish)
                //            {
                //                FormHelper.ApplicationShow(UI.MsgType.Information, "放样过程中读卡!启动样桶读卡");
                //                _b读写卡StarteReplenish = true;
                //                E_Rfid.DoRead(_strStm32ip, _strStm32Port, true);
                //            }
                //        }
                //    }
                //    else
                //        _b读写卡StarteReplenish = false;
                //}

                //判断是否开始放样
                if (_b读写卡Complete)
                {
                    if (_b读写卡Success)
                    {
                        _bNeedSend开始放样 = true;
                    }
                    else
                    {
                        FormHelper.ApplicationShow(UI.MsgType.Error, "读卡完成，样桶识别失败...");
                        _b读写卡Started = false;
                        /*
                        * 异常处理流程
                        */
                        _b读写卡Complete = false;
                    }
                }

                /*
                * 给封装机下发开始放样指令
                */
                if (_bNeedSend开始放样 && !_bSend开始放样)
                {
                    lock (_objLock开始放样)
                    {
                        FormHelper.ApplicationShow(UI.MsgType.Information, "当前需要给封装机下发开始放样指令，前提是封装机自动准备好!");
                        if (!_bSend开始放样 && CacheMemoryCenter.E_PackingMachineState.自动准备好)
                        {
                            if (Task.Fzj.Instance.DoWrite(52, (short)301))
                            {
                                _bSend开始放样 = true;
                                _bNeedSend开始放样 = false;
                                FormHelper.ApplicationShow(UI.MsgType.Information, "往封装机写入开始放样指令成功!");
                            }
                            else
                                FormHelper.ApplicationShow(UI.MsgType.Error, "往封装机写入开始放样指令失败!详见日志!");
                        }
                    }
                }

                ///*
                //* 肖波 230309
                //* 收到样桶开盖异常的情况下，需要重新换桶，并标记当前样桶作废
                //*/
                //if (CacheMemoryCenter.E_PackingMachineState.开盖异常)
                //{
                //    lock (_objLock开盖异常)
                //    {
                //        FormHelper.ApplicationShow(UI.MsgType.Waring, string.Format("当前样桶开盖异常，系统尝试将更{0}#桶标记失效，并尝试换新的样桶!", _modelSave.E_SamplingPail));
                //        DAL.SqlLite.Main.Instance.DoGiveupPail(_modelSave.E_SamplingPail);
                //        int _iSamplingPail = DAL.SqlLite.Main.Instance.DoGetPailForSampling(CacheMemoryCenter.E_SamplingInfo.En_Batch, CacheMemoryCenter.E_SamplingInfo.En_SamplingPosCount, CacheSamplingPacking.DoGetCachePointCount(), Math.Abs(E_SampleWeightNet));
                //        if (_iSamplingPail <= 0)
                //        {
                //            FormHelper.ApplicationShow(UI.MsgType.Waring, string.Format("当前样桶开盖异常，系统无法自动切换样桶，请手动出桶之后再操作!"));
                //            /*
                //            * 
                //            */
                //        }
                //        else
                //        {
                //            if (CacheMemoryCenter.E_PackingMachineState.自动准备好)
                //            {

                //            }
                //            if (!_bOpenPailErrorReSetCommand)
                //            {
                //                _modelSave.E_SamplingPail = _iSamplingPail;
                //                if (DoSendCommand())
                //                    _bOpenPailErrorReSetCommand = true;
                //            }
                //        }
                //    }
                //}

                /*
                * 肖波 230309
                * 放样结束的时候保存所有数据
                */
                if (CacheMemoryCenter.E_PackingMachineState.放样结束)
                {
                    LayingOffComplete();
                }


            }
            catch (Exception ex)
            {
                FormHelper.ApplicationShow(UI.MsgType.Error, "封装机管理界面出现未知异常!详见日志!");
                Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Error, Log.LogSubitem.Forms, "封装机管理界面出现未知异常!");
                Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Error, Log.LogSubitem.Forms, ex.ToString());
            }
            finally
            {
                _bIsBusy = false;
            }
        }


        /// <summary>
        /// 放样结束
        /// </summary>
        private void LayingOffComplete()
        {
            if (!_bSavePaiEnd)
            {
                if (_modelSave != null)
                {
                    if (DAL.SqlLite.Main.Instance.DoUpdateSamplingEndPail(_modelSave.E_SamplingPail, _modelSave.E_SamplingPoscount,
                        E_SampleWeightNet + Convert.ToDecimal("0.06"), _modelSave.E_SamplingBatchCode, _modelSave.E_SamplingPailCard, _modelSave.E_SamplingIdIfLocal))
                        FormHelper.ApplicationShow(UI.MsgType.Information, "样桶信息更新成功!");
                    else
                        FormHelper.ApplicationShow(UI.MsgType.Error, "样桶信息更新失败!详见日志!");
                    if(string.IsNullOrEmpty(_modelSave.E_SamplingPailCard))
                        FormHelper.ApplicationShow(UI.MsgType.Error, $"桶号：{_modelSave.E_SamplingPail}，没有读取到通号，请检查该样桶/检查网络情况/重启程序");

                    UI.FormHelper.SetControlText(labCurrentCar, string.Empty);
                    UI.FormHelper.SetControlText(labCurrentPail, string.Empty);

                    //当前为非串行作业的情况下封装完成后抬杆
                    if (!CacheSystemControl.E_SamplingSerialjob)
                    {
                        if (!Task.Cyj.Instance.DoWrite(100, (short)100))
                            FormHelper.ApplicationShow(UI.MsgType.Error, "出口道闸抬杆失败!建议手动抬杆!");
                        Voicer.Instance.DoSendSound("采样完成，请司机尽快将车辆驶离当前区域");
                    }

                    //释放所有控制变量
                    _bWeightTare = false;
                    _bWeightGross = false;
                    _bSendStartCmd = false;

                    CacheSamplingPacking.DoPackingDone();
                    _bSavePaiEnd = true;

                    //刷新样桶展示
                    ActionCenter.Action.Instance.DoRefreshSamplingPail();

                    //触发数据上传
                    UI_Operate.DataUpload.E_NeedUpload = true;

                    //样品称重预警
                    DoJudgeWeight(E_SampleWeightNet + Convert.ToDecimal("0.06"));
                }
                else
                {
                    FormHelper.ApplicationShow(UI.MsgType.Waring, "收到放样结束信号!当前并无封装信息!");
                }
            }
        }


        /// <summary>
        /// 
        /// </summary>
        private List<string> _listWeightWaring = new List<string>();
        /// <summary>
        /// 判断是否需要产生预警
        /// </summary>
        /// <param name="value"></param>
        private void DoJudgeWeight(decimal value)
        {
            bool _bShow = false;
            _listWeightWaring = new List<string>();
            _listWeightWaring.Add("1、当前为样品称重预警，提醒采样员关注采样缩分是否正常;");
            if (value < CacheSystemControl.E_SampleWeightMinValue)
            {
                _listWeightWaring.Add(string.Format("2、系统当前样品重量{0}kg小于预警值{1}kg;", value, CacheSystemControl.E_SampleWeightMinValue));
                _listWeightWaring.Add("3、建议如下：");
                _listWeightWaring.Add("第一步：检查采样机缩分频率是否正常;");
                _listWeightWaring.Add("第二步：检查封装机称重是否正常;");
                _listWeightWaring.Add("第三步：检查封装机落料管是否堵塞;可通过敲击声音判断;");
                _listWeightWaring.Add("第四步：检查采样螺旋是否取样正常;");
                _bShow = true;
            }
            else if (value > CacheSystemControl.E_SampleWeightMaxValue)
            {
                _listWeightWaring.Add(string.Format("2、系统当前样品重量{0}kg 大于预警值{1}kg;", value, CacheSystemControl.E_SampleWeightMaxValue));
                _listWeightWaring.Add("建议如下：");
                _listWeightWaring.Add("3、建议如下：");
                _listWeightWaring.Add("第一步：检查采样机缩分频率是否正常;");
                _listWeightWaring.Add("第二步：检查封装机称重是否正常;");
                _listWeightWaring.Add("第三步：检查封装机落料管是否堵塞;可通过敲击声音判断;");
                _listWeightWaring.Add("第四步：检查采样机弃料皮带是否堵塞;");
                _bShow = true;
            }
            if (_bShow)
                ActionCenter.Action.Instance.DoSendWarings(_listWeightWaring, false);

        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TabsPail_SelectedTabChanged(object sender, Infragistics.Win.UltraWinTabControl.SelectedTabChangedEventArgs e)
        {
            if (TabsPail.SelectedTab.Index == 2)
            {
                DoBindPails();
            }
            if (TabsPail.SelectedTab.Index == 0)
            {
                DoQueryPailsStatus();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridPail_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                var paiid = gridPail.Rows[e.RowIndex].Cells[0].Value.ToString().Replace("#桶", "");
                var painame = gridPail.Rows[e.RowIndex].Cells[0].Value.ToString();
                switch (gridPail.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString())
                {
                    case "复位":
                        if (MessageBox.Show(string.Format("是否确定复位{0}", painame), "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            if (DAL.SqlLite.Main.Instance.DoRestPail(paiid))
                            {
                                //清除全局缓存的桶号
                                CacheSamplingPacking.E_SamplingPailCardCache = new string[8] { "", "", "", "", "", "", "", "" };
                                MessageBox.Show("操作成功！");
                                DoBindPails();
                            }
                        }
                        break;
                    case "修改":
                        frmParameterSettings obj = new frmParameterSettings(gridPail.Rows[e.RowIndex]);
                        obj.ShowDialog();
                        DoBindPails();
                        break;
                    case "启用":
                        if (MessageBox.Show(string.Format("是否确定启用{0}", painame), "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            if (DAL.SqlLite.Main.Instance.DoSetPailStatus(paiid, true))
                            {
                                MessageBox.Show("操作成功！");
                                DoBindPails();
                            }
                        }
                        break;
                    case "禁用":
                        if (MessageBox.Show(string.Format("是否确定禁用{0}", painame), "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            if (DAL.SqlLite.Main.Instance.DoSetPailStatus(paiid, false))
                            {
                                MessageBox.Show("操作成功！");
                                DoBindPails();
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolPails_ToolClick(object sender, Infragistics.Win.UltraWinToolbars.ToolClickEventArgs e)
        {
            if (e.Tool.Key == "OnKey")
            {
                if (MessageBox.Show("是否确定复位所有样桶?", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    DAL.SqlLite.Main.Instance.DoRestPail(string.Empty);
                    //清除全局缓存的桶号
                    CacheSamplingPacking.E_SamplingPailCardCache = new string[8] { "", "", "", "", "", "", "", "" };
                    DoBindPails();
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void DoBindPails()
        {
            gridPail.DataSource = DAL.SqlLite.Main.Instance.DoQueryPailsForOperate();
            foreach (DataGridViewRow dgr in gridPail.Rows)
            {
                if (dgr.Cells["status"].Value.ToString().IndexOf("禁") >= 0)
                    dgr.Cells["status"].Style.ForeColor = Color.Red;
                else
                    dgr.Cells["status"].Style.ForeColor = Color.Green;
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void labLdWeight_DoubleClick(object sender, EventArgs e)
        {
        }

        private void btnResetDevice_Click(object sender, EventArgs e)
        {
            Task.Fzj.Instance.DoWrite(52, 200);
        }

        private void frmPail_FormClosing(object sender, FormClosingEventArgs e)
        {
        }

        private void btnResetError_Click(object sender, EventArgs e)
        {
            Task.Fzj.Instance.DoWrite(52, 201);

        }


        /// <summary>
        /// 读卡器异步事件
        /// </summary>
        /// <param name="send"></param>
        /// <param name="e"></param>
        private void OnReadCardStm32(object send, ActionCenter.CommonEventArgs e)
        {
            if (_b读写卡Need && _b读写卡Started)
            {
                Entity.StmResult _model = (Entity.StmResult)e.E_Values;
                if (_model != null)
                {
                    if (_model.E_Success)
                    {
                        if (_model.E_Cards != null)
                        {
                            if (_model.E_Cards.Count == 1)
                            {
                                _modelSave.E_SamplingPailCard = _model.E_Cards[0].E_Tid;
                                FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("读卡成功!识别到卡号{0}!", _model.E_Cards[0].E_Tid));
                                //只有在非只读模式下才算读卡成功，并触发后续流程动作
                                _b读写卡Success = true;
                            }
                            else
                            {
                                FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("读卡成功!系统成功读取到{0}张卡片!", _model.E_Cards.Count));
                                foreach (CardInfo card in _model.E_Cards)
                                {
                                    FormHelper.ApplicationShow(UI.MsgType.Error, string.Format("卡号:{0}  读取次数:{1}", card.E_Tid, card.E_Count));
                                }
                                _modelSave.E_SamplingPailCard = (_model.E_Cards.OrderByDescending(t => t.E_Count).ToList())[0].E_Tid;
                                FormHelper.ApplicationShow(UI.MsgType.Error, string.Format("系统采用卡片{0}作为当前卡号", _modelSave.E_SamplingPailCard));
                                _b读写卡Success = true;
                            }
                        }
                    }
                    else
                        FormHelper.ApplicationShow(UI.MsgType.Error, "第一次读卡失败，尝试再次读取!");
                }
                _b读写卡Complete = true;
            }
            _b读写卡Need = false;
            _b读写卡Started = false;

            /*
            * 加入补丁程序
            */
            Entity.StmResult _modelJustRead = (Entity.StmResult)e.E_Values;
            if (_modelJustRead != null)
            {
                if (_modelJustRead.E_JustRead && _modelJustRead.E_Success)
                {
                    if (_modelJustRead.E_Cards != null)
                    {
                        if (_modelJustRead.E_Cards.Count == 1)
                        {
                            _modelSave.E_SamplingPailCard = _modelJustRead.E_Cards[0].E_Tid;
                            FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("读卡成功!识别到卡号{0}!", _modelJustRead.E_Cards[0].E_Tid));
                            //只有在非只读模式下才算读卡成功，并触发后续流程动作
                            _b读写卡Success = true;
                        }
                        else
                        {
                            FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("读卡成功!系统成功读取到{0}张卡片!", _modelJustRead.E_Cards.Count));
                            foreach (CardInfo card in _modelJustRead.E_Cards)
                            {
                                FormHelper.ApplicationShow(UI.MsgType.Error, string.Format("卡号:{0}  读取次数:{1}", card.E_Tid, card.E_Count));
                            }
                            _modelSave.E_SamplingPailCard = (_modelJustRead.E_Cards.OrderByDescending(t => t.E_Count).ToList())[0].E_Tid;
                            FormHelper.ApplicationShow(UI.MsgType.Error, string.Format("系统采用卡片{0}作为当前卡号", _modelSave.E_SamplingPailCard));
                            _b读写卡Success = true;
                        }
                    }
                }
            }

            #region 读取样桶卡号失败的补救措施
            try
            {
                
                //将此次读到的卡号 缓存到E_SamplingPailCardCache对应桶号的索引位置
                int pailIndex = _modelSave.E_SamplingPail - 1;
                if (!string.IsNullOrEmpty(_modelSave.E_SamplingPailCard))//当前读到了卡号
                {
                    if (_modelSave.E_SamplingPail > 0 && _modelSave.E_SamplingPail <= 6)
                        //if (string.IsNullOrEmpty(CacheSamplingPacking.E_SamplingPailCardCache[pailIndex]))//如果当前缓存索引位置没有存卡号，则更新
                        CacheSamplingPacking.E_SamplingPailCardCache[pailIndex] = _modelSave.E_SamplingPailCard;
                }
                else
                {
                    //没有读到卡号，就去拿对应桶号缓存位置的 卡号
                    if (!string.IsNullOrEmpty(CacheSamplingPacking.E_SamplingPailCardCache[pailIndex]))
                        _modelSave.E_SamplingPailCard = CacheSamplingPacking.E_SamplingPailCardCache[pailIndex];
                    FormHelper.ApplicationShow(UI.MsgType.Waring, "样桶补卡成功!");
                    Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Program, Log.LogSubitem.Log, $"没有读到{_modelSave.E_SamplingPail}号桶卡号，用上次读取值替补：{_modelSave.E_SamplingPailCard}");
                }


            }
            catch (Exception ex)
            {
                Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Error, Log.LogSubitem.Log, $"替补桶号时，发生异常");
                Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Error, Log.LogSubitem.Log, ex.ToString());
            }
            #endregion
        }

        /// <summary>
        /// 
        /// </summary>
        private void SetUI_OpenClose()
        {
            oc写卡触发.C_Value = CacheMemoryCenter.E_PackingMachineState.写卡触发 ? UI.TwoStateValue.On : UI.TwoStateValue.Off;
            oc准备好.C_Value = CacheMemoryCenter.E_PackingMachineState.准备好 ? UI.TwoStateValue.On : UI.TwoStateValue.Off;
            oc复位运行.C_Value = CacheMemoryCenter.E_PackingMachineState.复位运行 ? UI.TwoStateValue.On : UI.TwoStateValue.Off;
            oc手动模式.C_Value = CacheMemoryCenter.E_PackingMachineState.手动模式 ? UI.TwoStateValue.On : UI.TwoStateValue.Off;
            oc放样结束.C_Value = CacheMemoryCenter.E_PackingMachineState.放样结束 ? UI.TwoStateValue.On : UI.TwoStateValue.Off;
            oc放样运行.C_Value = CacheMemoryCenter.E_PackingMachineState.放样运行 ? UI.TwoStateValue.On : UI.TwoStateValue.Off;
            oc称重触发.C_Value = CacheMemoryCenter.E_PackingMachineState.称重触发 ? UI.TwoStateValue.On : UI.TwoStateValue.Off;
            oc自动模式.C_Value = CacheMemoryCenter.E_PackingMachineState.自动模式 ? UI.TwoStateValue.On : UI.TwoStateValue.Off;
        }



    }
}
